//
//  UserAuthenticator.swift
//  hello
//
//  Created by yafei li on 2025/9/18.
//

import JWT
import Vapor

struct UserAuthenticator: JWTAuthenticator {
    typealias Payload = UserPayload
    // ✅ 你现在可以专注于业务逻辑
    func authenticate(jwt: UserPayload, for request: Request) async throws {
        
        //  检测Token是否在黑名单中
        let tokenBlackList = TokenBlackList()
        
        let token = request.headers.bearerAuthorization!.token
//        print("token:",token)
        let tokenHash = SHA256.hash(data: Data(token.utf8)).description.base64String()
        
        let isExist = try await tokenBlackList.exists(tokenHash: tokenHash, on: request)
        
        if isExist {
            throw Abort.tokenInvalid
        }else{
            // ✅ 注入用户到请求上下文
            request.auth.login(jwt)
        }
    }
}
